package com.swgk.core.mmkvutil;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.swgk.core.mmkvutil.MkvUtils;

import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class DatalUtils {
    public static <D> boolean isEmpty(List<D> list) {
        return list == null || list.isEmpty();
    }

    private static DatalUtils datalUtils;
    public static Gson gson;

    public static DatalUtils getInstance() {
        if (datalUtils == null) {
            datalUtils = new DatalUtils();
            gson = new Gson();
        }
        return datalUtils;
    }

    /**
     * 获取缓存数据
     * 集合类型
     *
     * @param message:缓存类别
     * @param cls：数据类型
     * @param <T>
     * @return
     */
    public static <T> List<T> jsonToDtoList(String name, String message, Class<T> cls) {
        String cacheCahcegoryModelData = MkvUtils.get().getString(message);
        List<T> list = new ArrayList<T>();
        try {
            JsonArray arry = new JsonParser().parse(cacheCahcegoryModelData).getAsJsonArray();
            for (JsonElement jsonElement : arry) {
                list.add(gson.fromJson(jsonElement, cls));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * @param message
     * @param cls
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T jsonToDto(String message, Class<T> cls) {
        String cacheCahcegoryModelData = MkvUtils.get().getString(message);
        T t = null;
        try {
            t = gson.fromJson(cacheCahcegoryModelData, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return t;
    }


    /**
     * @param tagKey
     * @param type   例如：Type type = new TypeToken<List<MenuEntity>>() {}.getType();
     * @return 解析为要得到的实体
     */
    public <T> T  getData(String tagKey, Type type) {
        String dataValue = MkvUtils.get().getString(tagKey);
        return gson.fromJson(dataValue, type);
    }

    public String getJsonString(Object obj) {
        return gson.toJson(obj);
    }


    public Object getData(String tag,String tagKey, Type type){
        try {
            String cacheVideoTapeData = MkvUtils.get().getString(tag,tagKey, "");
            if (TextUtils.isEmpty(cacheVideoTapeData)){
                return null;
            }
            return gson.fromJson(cacheVideoTapeData,type);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     *
     * @param tagKey
     * @param typeToken 例如：Type type = new TypeToken<List<MenuEntity>>() {}.getType();
     * @return 解析为要得到的实体
     */
    public <T> T getData(String tag,String tagKey, TypeToken<T> typeToken ){
        try {
            String cacheVideoTapeData = MkvUtils.get().getString(tag,tagKey, "");
            if (TextUtils.isEmpty(cacheVideoTapeData)){
                return null;
            }
            return gson.fromJson(cacheVideoTapeData, typeToken.getType());
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 数据存储
     *
     * @param tagKey
     * @param dataValue 对象
     */
    public void putData(String tagKey, Object dataValue) {
        String data = gson.toJson(dataValue);
        MkvUtils.get().putString(tagKey, data);
    }

    /**
     * 数据存储
     *
     * @param tagKey
     * @param dataValue 对象
     */
    public void putData(String tag, String tagKey, Object dataValue){
        String data = gson.toJson(dataValue);
        MkvUtils.get().putString(tag,tagKey, data);
    }

    /**
     * 数据存储
     * @param tagKey
     * @param dataValue 字符串
     */
    public void putData(String tagKey, String dataValue) {
        MkvUtils.get().putString(tagKey, dataValue);
    }

    /**
     *
     * @param tagKey
     * @return 获取字符串
     */
    public String getData(String tagKey){
        String dataValue = MkvUtils.get().getString(tagKey,"");
        return dataValue;
    }
    /**
     * 数据存储
     * @param tagKey
     * @param dataValue 字符串
     */
    public void  putData(String tag,String tagKey,String dataValue){
        MkvUtils.get().putString(tag,tagKey, dataValue);
    }

    /**
     *
     * @param tagKey
     * @return 解析为要得到的实体
     */
    public String getData(String tag,String tagKey){
        String dataValue = MkvUtils.get().getString(tag,tagKey,"");
        return dataValue;
    }


    /**
     * 获取字符串的哈希值
     */
    public String strToHashKey(Object t) {
        String tmpKey;
        String k = "";
        try {
            k = gson.toJson(t);
            MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(k.getBytes());
            tmpKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            tmpKey = String.valueOf(k.hashCode());
        }
        return tmpKey;
    }

    /**
     * 获取缓存哈希值（用于json字符串哈希值对比）
     *
     * @param mCacheCateGory 缓存类型
     * @return
     */

    public static String getHashData(String cacheName, String mCacheCateGory) {
        //根据缓存类型获取json缓存数据
        String cacheCahcegoryModelData = MkvUtils.get().getString(cacheName, mCacheCateGory, "");

        //拿到字符串的哈希值
        String mHash = strToHashKey(cacheCahcegoryModelData);
        return mHash;
    }

    /**
     * 获取字符串的哈希值
     */
    public static String strToHashKey(String k) {
        String tmpKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(k.getBytes());
            tmpKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            tmpKey = String.valueOf(k.hashCode());
        }
        return tmpKey;
    }

    private static String bytesToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(0xFF & b[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();

    }

    /**
     * 判断缓存的哈希值与网络获取的哈希值是否相等 true 相等  false 不相等
     * @param object  转换的实体类
     * @param CacheName  获取缓存的key
     * @return
     */
    public boolean IsCahceEqual(Object object, String CacheName) {
        //获取现在数据json
        String dataJson = DatalUtils.getInstance().getJsonString(object);
        //转换哈希值
        String mHashNet = DatalUtils.strToHashKey(dataJson);
        //获取缓存并转换哈希值
        String hashData = DatalUtils.getHashData(MkvUtils.CacheModular, CacheName);
        if (mHashNet.equals(hashData)) {
            return true;
        }
        MkvUtils.get().putString(MkvUtils.CacheModular, CacheName, dataJson);
        return false;
    }
}
